package city.spring.modules.material.controller;

import city.spring.modules.material.entity.MaterialwarehousingEntity;
import city.spring.modules.material.service.MaterialSettingService;
import city.spring.modules.material.service.MaterialwarehousingService;
import city.spring.modules.material.service.StorehouseService;
import city.spring.modules.material.service.SupplierService;
import city.spring.modules.material.vo.MaterialwarehousingVO;
import city.spring.modules.material.vo.PrintWarehousingVO;
import city.spring.modules.personnel.service.EmployeeService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.NonNull;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Controller：入库信息
 *
 * @author 谢金婷
 * @date 2020-04-08 12:05:00
 */
@RestController
@RequestMapping("/warehousing")
public class MaterialwarehousingController extends ApiController {

    private final MaterialwarehousingService materialwarehousingService;
    private final StorehouseService storehouseService;
    private final EmployeeService employeeService;
    private final MaterialSettingService materialSettingService;
    private final SupplierService supplierService;

    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MaterialwarehousingEntity, ?>> entityOrderFields;

    public MaterialwarehousingController(MaterialwarehousingService materialwarehousingService, StorehouseService storehouseService, EmployeeService employeeService, MaterialSettingService materialSettingService, SupplierService supplierService) {
        this.materialwarehousingService = materialwarehousingService;
        this.storehouseService = storehouseService;
        this.employeeService = employeeService;
        this.materialSettingService = materialSettingService;
        this.supplierService = supplierService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MaterialwarehousingEntity::getId);
        entityOrderFields.add(MaterialwarehousingEntity::getMaterialSource);
        entityOrderFields.add(MaterialwarehousingEntity::getStorehouseId);
        entityOrderFields.add(MaterialwarehousingEntity::getWarehousingdate);
        entityOrderFields.add(MaterialwarehousingEntity::getUserId);
    }

    /**
     * 获取全部的 <strong>入库信息</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, MaterialwarehousingEntity entity) {
        LambdaQueryChainWrapper<MaterialwarehousingEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>入库信息</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, MaterialwarehousingVO entity, Date[] warehousingdate) {

        QueryWrapper<? extends MaterialwarehousingEntity> queryWrapper = buildQuery(entity);
        if (warehousingdate != null && warehousingdate.length == 2) {
            queryWrapper.ge("t1.warehousingdate", warehousingdate[0]);
            queryWrapper.le("t1.warehousingdate", warehousingdate[1]);
        }
        return success(materialwarehousingService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));


//        LambdaQueryChainWrapper<MaterialwarehousingEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//
//        if (warehousingdate1 != null && warehousingdate2 != null) {
//            lambdaQuery.ge(MaterialwarehousingEntity::getWarehousingdate, warehousingdate1);
//            lambdaQuery.le(MaterialwarehousingEntity::getWarehousingdate, warehousingdate2);
//        }
//
//        Page<MaterialwarehousingEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        for (MaterialwarehousingEntity record : page.getRecords()) {
//            try {
//                StorehouseEntity storehouseEntity = storehouseService.getById(record.getStorehouseId());
//                record.setSname(storehouseEntity.getSname());
//            } catch (Exception ignore) {
//                record.setStorehouseId(null);
//                record.setSname("< 找不到仓库 >");
//            }
//        }
//        for (MaterialwarehousingEntity record : page.getRecords()) {
//            try {
//                EmployeeEntity employeeEntity = employeeService.getById(record.getUserId());
//                record.setName(employeeEntity.getName());
//            } catch (Exception ignore) {
//                record.setUserId(null);
//                record.setName("< 找不到经办人 >");
//            }
//        }
//        for (MaterialwarehousingEntity record : page.getRecords()) {
//            try {
//                MaterialSettingEntity materialSettingEntity = materialSettingService.getById(record.getMaterialId());
//                record.setMname(materialSettingEntity.getName());
//            } catch (Exception ignore) {
//                record.setMaterialId(null);
//                record.setMname("< 找不到物资 >");
//            }
//        }
//        for (MaterialwarehousingEntity record : page.getRecords()) {
//            try {
//                SupplierEntity supplierEntity = supplierService.getById(record.getSupplierId());
//                record.setSuppliername(supplierEntity.getSuppliername());
//            } catch (Exception ignore) {
//                record.setSupplierId(null);
//                record.setSuppliername("< 找不到供应商 >");
//            }
//        }
//        return success(page);
    }

    /**
     * 获取一个 <strong>入库信息</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
//        return success(materialwarehousingService.getShelflevelWarehousingById(id));
        QueryWrapper<MaterialwarehousingVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MaterialwarehousingVO> records = materialwarehousingService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }


    /**
     * 添加一个 <strong>入库信息</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody MaterialwarehousingEntity entity, @NonNull Principal user) {
        materialwarehousingService.saveWarehousing(entity, user);

//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
//        return new ResponseEntity<>(headers, HttpStatus.CREATED);
        return success(entity);
    }

    /**
     * 修改一个 <strong>入库信息</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody MaterialwarehousingEntity entity) {
        entity.setId(id);

        materialwarehousingService.updateWarehousing(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>入库信息</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        materialwarehousingService.deleteWarehousing(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>入库信息</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        materialwarehousingService.deleteWarehousing(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MaterialwarehousingEntity> buildLambdaQuery(MaterialwarehousingEntity entity) {
        LambdaQueryChainWrapper<MaterialwarehousingEntity> lambdaQuery = materialwarehousingService.lambdaQuery();
        lambdaQuery.eq(entity.getId() != null, MaterialwarehousingEntity::getId, entity.getId());
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getMaterialSource()), MaterialwarehousingEntity::getMaterialSource, entity
                .getMaterialSource());
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getStorehouseId()), MaterialwarehousingEntity::getStorehouseId, entity.getStorehouseId());
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getSname()), MaterialwarehousingEntity::getSname, entity
                .getSname());
        lambdaQuery.like(entity.getWarehousingdate() != null, MaterialwarehousingEntity::getWarehousingdate, entity.getWarehousingdate());
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getName()), MaterialwarehousingEntity::getName, entity.getName());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MaterialwarehousingEntity> buildQuery(MaterialwarehousingVO entity) {
        QueryWrapper<MaterialwarehousingEntity> wrapper = new QueryWrapper<>();
        wrapper.like(entity.getId() != null, "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getWarehouseId()), "t1.warehouse_id", entity.getWarehouseId());
        wrapper.like(StringUtils.isNotBlank(entity.getStorehouseId()), "t1.storehouse_id", entity.getStorehouseId());
        wrapper.like(StringUtils.isNotBlank(entity.getSname()), "t3.sname", entity.getSname());
        wrapper.like(StringUtils.isNotBlank(entity.getUserId()), "t1.user_id", entity.getUserId());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t2.name", entity.getName());
//        wrapper.like(entity.getApplicationdate() != null, "t3.applicationdate", entity.getApplicationdate());
        return wrapper;
    }

    /**
     * 入库单作废
     *
     * @param id
     * @param entity
     * @return
     */
    @PutMapping("/checkCancellation/{id}")
    public Object checkCancellation(@PathVariable String id, @RequestBody MaterialwarehousingEntity entity) {
        materialwarehousingService.checkCancellation(id, entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 打印入库单
     *
     * @param ids
     * @return
     */
    @PostMapping("/getPrintWarehousing")
    public Object getPrintWarehousing(@RequestBody List<String> ids) {
        PrintWarehousingVO data = materialwarehousingService.getPrintWarehousing(ids);
        return success(data);
    }
}
